const express = require("express");
const router = express.Router();
const adminsDao = require("../dao/mysql/AdminsDao");
const usersDao = require("../dao/mysql/UsersDao");
//html后缀，表示请求的页面
router.get("/logout.do", (req, res) => {
  res.json({
    code: 200,
    msg: "注销成功",
  });
});

router.post("/modifyPassword.do", (req, res, next) => {
  if (req.body.type) {
      let type = req.body.type;
      let obj = {};
      obj.id = req.body.id;
      if (type == "0") {
          obj.apassword = req.body.newPassword
          adminsDao.update(obj).then(data => {
              res.json({
                  code: 200,
                  msg: "修改成功"
              })
          });
      } else if (type == "1") {
          obj.upassword = req.body.newPassword
          usersDao.update(obj).then(data => {
              res.json({
                  code: 200,
                  msg: "修改成功"
              })
          });
      } else if (type == "2") {
          obj.upassword = req.body.newPassword
          usersDao.update(obj).then(data => {
              res.json({
                  code: 200,
                  msg: "修改成功"
              })
          });

      }
  }
});

//do后缀，表示处理请求
router.post("/login.do", (req, res, next) => {
  //获取提交的数据
  const { upassword, uaccount, rem, type } = req.body;
  if(!uaccount){
    return res.json({
      code: 500,
      msg: "账号不能为空",
    });
  }
  if(!upassword){
    return res.json({
      code: 500,
      msg: "密码不能为空",
    });
  }
  //数据验证
  if (uaccount.trim().length < 1) {
    return res.json({
      code: 500,
      msg: "账号长度必须大于等于两位",
    });
  }
  if ( upassword.length < 3) {
    return res.json({
      code: 500,
      msg: "密码长度必须大于3位",
    });
  }
  if (!type) {
    return res.json({
      code: 500,
      msg: "请选择用户类型",
    });
  }
  let result; //登录查询结果
  let msg; //登录用户信息
  if (type == "0") {
    result = adminsDao.login(uaccount, upassword);
    msg = "系统管理员：";
  } else if (type == "1") {
    result = usersDao.login(uaccount, upassword);
    msg = "登陆成功";
  } else if (type == "2") {
    result = usersDao.login(uaccount, upassword);
    msg = "登陆成功";
  } else {
    return res.json({
      code: 500,
      msg: "用户类型错误",
    });
  }
  if (result) {
    result
      .then(data => {
        let taccount = "";
        console.log('登陆数据',data);
        if (!data) {
          return res.json({
            code: 404,
            msg: "账号或密码错误",
          });
        }
        if (data.aaccount) {
          taccount = data.aaccount;
          tpassword = data.apassword
        } else {
          taccount = data.uaccount;
          tpassword = data.upassword
        }
        if (rem == "1") {
          //req.cookies，获取所有cookie
          //在cookie中保存账号和密码
          //res，响应对象
          res.cookie("account", taccount, {
            maxAge: 1000 * 60 * 60 * 24 * 7,
            signed: true,
          }); //maxAge单是毫秒
          res.cookie("password", tpassword, {
            maxAge: 1000 * 60 * 60 * 24 * 7,
            signed: true,
          });
        } else {
          // res.cookie("account", "");
          // res.cookie("password", "");
          res.clearCookie("taccount");
          res.clearCookie("tpassword");
        }
        let app = res.app.locals;
        //登录成功重定向到/admins/list.html
        res.json({
          code: 200,
          msg,
          // 调用 jwt.sign() 生成 JWT 字符串，三个参数分别为：用户信息对象，加密密钥，配置对象
          token:
            "Bearer " +
            app.jwt.sign(
              {
                account: taccount,
                uname: data.uname,
                id: data.id,
                type: type,
                role: data.role,
              },
              app.secretKey,
              { expiresIn: "7days" }
            ),
        });
      })
      .catch(err => next(err));
  } else {
    return res.json({
      code: 404,
      msg: "账号或密码错误",
    });
  }
});

router.get("/getInfo.do", (req, res, next) => {
  console.log("/getInfo.do");
  // 查询角色菜单
  // res.app.locals.menus = data;
  // res.app.locals.menu_active = 0;//当前选中的菜单项
  res.json({
    code: 200,
    data: {
      //expressJWT会解析token放到req.user
      loginUser: req.user,
    },
  });
});

module.exports = router;
